package cn.yzstu.processor;

import com.google.auto.service.AutoService;
import com.sun.source.tree.Tree;
import com.sun.source.util.Trees;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.processing.JavacProcessingEnvironment;
import com.sun.tools.javac.tree.JCTree;
import com.sun.tools.javac.tree.TreeMaker;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.Name;
import com.sun.tools.javac.util.Names;

import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic;
import java.util.Set;

/**
 * Processor的一些公有方法
 * @author Baldwin
 */
@AutoService(Processor.class)
@SupportedAnnotationTypes("YzLogger")
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class YzLoggerProcessor extends AbstractProcessor {

    private Trees trees;
    private TreeMaker make;
    private Name.Table names;
    private int tally;
    private Context context;

    @Override
    public synchronized void init(ProcessingEnvironment processingEnv) {
        super.init(processingEnv);
        trees = Trees.instance(processingEnv);
        context = ((JavacProcessingEnvironment) processingEnv).getContext();
        make = TreeMaker.instance(context);
        names = Names.instance(context).table;
        tally = 0;
    }

    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        Set<? extends Element> elements = roundEnv.getRootElements();
        System.out.println("dsssfsdf");
        processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "reeor");
        processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "Hello World!");
        for (Element element : elements) {
            ElementKind kind = element.getKind();
            if (kind != ElementKind.METHOD) {
                continue;
            }

            Symbol.MethodSymbol methodSymbol = (Symbol.MethodSymbol) element;
            String methodName = methodSymbol.getSimpleName().toString();
            Tree methodTree = trees.getTree(element);
            if (methodTree == null) {
                continue;
            }
            processMethod(methodTree,  methodName);

        }
        return true;
    }

    private void processMethod(Tree methodTree, String methodName) {
        JCTree.JCMethodDecl methodJCTree = (JCTree.JCMethodDecl) methodTree;
        methodJCTree.accept(new YzLoggerTranslator(trees, make, names, context, methodName));
    }
}
